package com.lostandfound.action;

//import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.springframework.beans.factory.annotation.Autowired;

import com.lostandfound.entity.User;
//import com.lostandfound.filter.OnLineUsers;
//import com.lostandfound.service.TopicService;
import com.lostandfound.service.UserService;
import com.lostandfound.util.ReturnCode;
import com.opensymphony.xwork2.ActionSupport;

@Namespace("/")
@ParentPackage("json-default")  
@Results({  
    @Result(name="resJson", type = "json", params = {"root", "res"})  
})  
@SuppressWarnings("serial")
public class UserAction extends ActionSupport{
	
	@Autowired    
    private UserService userSerivce;
	/*@Autowired
	private TopicService topicService; */
	
	private User user;
	private Map<String,Object> res = new HashMap<String,Object>();
	private HashMap<String, Object> pagemap;//分页信息
	public HashMap<String, Object> getPagemap() {
		return pagemap;
	}

	public void setPagemap(HashMap<String, Object> pagemap) {
		this.pagemap = pagemap;
	}

	public Map<String, Object> getRes() {
		return res;
	}

	public void setRes(Map<String, Object> res) {
		this.res = res;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}
	
	/**
	 * 用户登录
	 * @return
	 */
	@Action(value="login")
	public String login(){
		if(user != null) {
			String password = user.getPassword();
			String type = user.getType();
			user = userSerivce.selectByUserCode(user.getUserCode());
			if(user != null){
				if(!password.equals(user.getPassword())){
					res.put("code", "999999");//登录失败(密码错误)
				}else{
					if(user.getStatus().equals("0")){
						if(!"0".equals(type)) {
							if(Integer.valueOf(user.getType()) < Integer.valueOf(type)) {
								res.put("code", "-1");//没有权限
							}else {
								res.put("code", "1");//登录成功
								ServletActionContext.getRequest().getSession().setAttribute("loginUser", user);
								/*Collection<HttpSession> collection = OnLineUsers.getInstance().getSessions();
								for (HttpSession httpSession : collection) {
									User login = (User)httpSession.getAttribute("loginUser");
									System.out.println(login.getUserCode());
								}*/
							}
						}else {
							res.put("code", "0");
							ServletActionContext.getRequest().getSession().setAttribute("loginUser", user);
						}
					}else{
						res.put("code", "100000");//登录失败(用户不存在)
					}
				}
			}else{
				res.put("code", "999999");//登录失败(用户名错误)
			}/*
			if(!password.equals(user.getPassword())) {
				res.put("code", "999999");//登录失败
			}else {
				ServletActionContext.getRequest().getSession().setAttribute("loginUser", user);
				res.put("code", "0");//正常登录
			}*/
		}
		return "resJson";
	}
	
	/**
	 * 注册用户
	 * @return
	 */
	@Action(value="register")
	public String register(){
		if(user != null){
			user.setCreateDate(new Date());
			user.setType("0");
			user.setStatus("1");
			try {
				userSerivce.save(user);
				res.put("code", ReturnCode.SUCCESS);//成功跳转登录页
			} catch (Exception e) {
				res.put("code", ReturnCode.FAIL);//失败重新注册
			}
			return "resJson";
		}
		res.put("code", ReturnCode.LOST_NEWS);//重新注册
		return "resJson";
	}
	
	/**
	 * 用户注销
	 * @return
	 */
	@Action(value="logout")
	public String logout(){
		ServletActionContext.getRequest().getSession().removeAttribute("loginUser");
		ServletActionContext.getRequest().getSession().removeAttribute("id");//注销session中的id对象
		ServletActionContext.getRequest().getSession().invalidate();//关闭session 
		res.put("code", "000000");
		return "resJson";//跳转登录页
	}
	
	/**
	 * 判断新增的账号是否可用
	 * @return
	 */
	@Action(value="isUserExist")
	public String isUserExist(){
		if(userSerivce.selectByUserCode(user.getUserCode())!=null){
			res.put("isUserExist", true);//账号已被占用
		}else{
			res.put("isUserExist", false);//账号可用
		}
		return "resJson";
	}
	
	/**
	 * 分页获取user列表
	 * @return
	 */
	@Action(value="listUser")
	public String listUser(){
		User loginUser = (User)ServletActionContext.getRequest().getSession().getAttribute("loginUser");
		if(loginUser != null){//判断是否是登录状态
			if(pagemap == null){//pagemap存放分页属性
				pagemap = new HashMap<String, Object>();
				pagemap.put("page", "1");
				pagemap.put("size", "10");
			}/*else{
				if(pagemap.get("mindate") != null && 
						!pagemap.get("mindate").equals("") && 
						pagemap.get("maxdate") != null && 
						!pagemap.get("maxdate").equals("") ){
					SimpleDateFormat sdf =   new SimpleDateFormat( " yyyy-MM-dd HH-mm-ss" );
			        String mindate = sdf.format(new Date().parse((String)pagemap.get("mindate")));
			        String maxdate = sdf.format(new Date().parse((String)pagemap.get("maxdate")));
			        pagemap.put("mindate", mindate);
			        pagemap.put("maxdate", maxdate);
				}
			}*/
			try {
				@SuppressWarnings("unchecked")
				List<User> listtopic = (List<User>)userSerivce.listUserByPage(pagemap);//分页查询主贴信息
				int count = userSerivce.Count(pagemap);
				this.res.put("userList", listtopic);
				this.res.put("usercount",count);//获取总条目
				int size = Integer.parseInt((String)pagemap.get("size"));
				this.res.put("userpage",count%size>0?count/size+1:count/size);//获取总页数
				this.res.put("code", ReturnCode.SUCCESS);//查询成功，跳转主贴列表显示页
			} catch (Exception e) {
				System.out.println("查询失败！");
				this.res.put("code", ReturnCode.FAIL);//查询失败，返回主页
			}
			return "resJson";
		}
		this.res.put("code", ReturnCode.LOST_NEWS);//用户未登录，跳转登录页
		System.out.println("--请登录--");//没有登录则跳转登录页面
		return "resJson";
	}
	
	/**
	 * 超管添加用户
	 * @return
	 */
	@Action(value="save")
	public String save(){
		if(user != null){
			user.setCreateDate(new Date());
			try {
				userSerivce.save(user);
				res.put("code", ReturnCode.SUCCESS);//成功跳转用户列表
			} catch (Exception e) {
				res.put("code", ReturnCode.FAIL);//失败重新新增
			}
			return "resJson";
		}
		res.put("code", ReturnCode.LOST_NEWS);//重新新增
		System.out.println("user");
		return "resJson";
	}

	
	/**
	 * 根据ID获取用户信息
	 * @return
	 */
	@Action(value="getUserById")
	public String getUserById(){
		if(user != null){
			Long uid = user.getId();
			try {
				user = userSerivce.selectByPrimary(uid);
				this.res.put("user", user);
				this.res.put("code", ReturnCode.SUCCESS);//查询成功
			} catch (Exception e) {
				System.out.println("获取板块信息失败！");
				this.res.put("code", ReturnCode.FAIL);//查询失败
			}
			return "resJson";
		}
		this.res.put("code", ReturnCode.LOST_NEWS);//输入有误
		return "resJson";
	}
	
	/**
	 * 修改用户信息
	 * @return
	 */
	@Action(value="updateUser")
	public String updateUser(){
		if(user != null){
			try {
				User newUser = userSerivce.selectByPrimary(user.getId());
				newUser.setEmail(user.getEmail());
				newUser.setPassword(user.getPassword());
				newUser.setTel(user.getTel());
				newUser.setEmail(user.getEmail());
				newUser.setUserName(user.getUserName());
				newUser.setStatus(user.getStatus());
				
				userSerivce.update(newUser);
				this.res.put("code", ReturnCode.SUCCESS);//修改成功，跳转用户列表
			} catch (Exception e) {
				this.res.put("code", ReturnCode.FAIL);//修改失败，停留当前页
			}
			return "resJson";
		}
		this.res.put("code", ReturnCode.LOST_NEWS);//信息不能为空
		return "resJson";
	}
	
	/**
	 * 批量删除用户
	 * @return
	 */
	@Action(value="deleteUser")
	public String deleteUser(){
		if(this.res != null && this.res.get("ids") != null){
			System.out.println(this.res.get("ids"));
	
			String[] ids = (String[])this.res.get("ids");
			
			String uids = ids[0]; 
			uids = uids.substring(1, uids.length()-1);
			String[] id = uids.split(",");
			if(id != null && id.length >0){
				Long[] u_ids = new Long[id.length];
				for (int i=0;i<id.length;i++) {
					//System.out.println(id[i]);
					Long l1 = Long.parseLong(id[i]);
					u_ids[i] = l1;
				}
				try {
					/*for (Long long1 : u_ids) {
						topicService.deleteTopicByUser(long1);//先删除用户下的主贴
					}*/
					userSerivce.deleteUserByBranch(u_ids);//再删除用户
					this.res.put("code", ReturnCode.SUCCESS);//删除成功，页面清除指定删除项
				} catch (Exception e) {
					e.printStackTrace();
					System.out.println("删除用户信息失败！");
					this.res.put("code", ReturnCode.FAIL);//删除失败，请重试
				}
				return "resJson";
			}
		}
		this.res.put("code", ReturnCode.LOST_NEWS);//输入有误,请选择要删除的用户
		return "resJson";
	}
	
	
	
}